package base

import "time"

// SysInfo 系统信息
type SysInfo struct {
	DataType    string    `db:"DATP" json:"type"`
	SYSDate     time.Time `db:"SYDT" json:"date"`
	IsImporting bool      `db:"ISPS" json:"-"`
}

// GetSysInfo 获取系统信息
func GetSysInfo() (infos []SysInfo, err error) {
	strSQL := `select DATP,SYDT,ISPS from T_CONF_SYDT`
	rows, err := MYDB.Raw(strSQL).Rows()
	if err != nil {
		return nil, err
	}
	infos = make([]SysInfo, 0, 4)
	for rows.Next() {
		var dtype string
		var date time.Time
		var issp bool
		rows.Scan(&dtype, &date, &issp)
		infos = append(infos, SysInfo{DataType: dtype, SYSDate: date, IsImporting: issp})
	}
	return
}

// GetSYSDate 根据类型获取系统日期
func GetSYSDate(dataType string) (sysDate *time.Time, IsImporting bool, err error) {
	hkey := "sysdate"
	dateStr := RedisCli.HGet(rctx, hkey, dataType).Val()
	if dateStr == "" {
		strSQL := `select SYDT,ISPS from T_CONF_SYDT where DATP=?`
		row := MYDB.Raw(strSQL, dataType).Row()
		err = row.Scan(&sysDate, &IsImporting)
		RedisCli.HSet(rctx, hkey, dataType, sysDate.Format("20060102"))
		RedisCli.Expire(rctx, hkey, 1*time.Hour)
	} else {
		date, _ := time.Parse("20060102", dateStr)
		sysDate = &date
	}
	return
}

// BeginImport 开始数据导入
func BeginImport(dataType string) error {
	strSQL := `update T_CONF_SYDT set ISPS=1 where DATP=?`
	err := MYDB.Exec(strSQL, dataType).Error
	return err
}

// FinishImport 完成数据导入
func FinishImport(dataType string, dataDate *time.Time) error {
	strSQL := `update T_CONF_SYDT set ISPS=0,SYDT=? where DATP=?`
	err := MYDB.Exec(strSQL, dataDate, dataType).Error
	return err
}
